package com.cn.client;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

public class SearchClient {

  private static RestHighLevelClient client;

  static {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "test-user-password"));
    RestClientBuilder restClientBuilder = RestClient.builder(
            new HttpHost("10.211.55.6", 9200),
            new HttpHost("10.211.55.3", 9200))
            .setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
              @Override
              public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                return requestConfigBuilder
                        .setConnectTimeout(6000)
                        .setSocketTimeout(6000);
              }
            })
            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
              @Override
              public HttpAsyncClientBuilder customizeHttpClient(
                      HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder
                        .setDefaultCredentialsProvider(credentialsProvider)
                        .setDefaultIOReactorConfig(
                                IOReactorConfig.custom()
                                        .setIoThreadCount(50)
                                        .build());
              }
            });
    client = new RestHighLevelClient(restClientBuilder);
  }

  public static RestHighLevelClient client() {
    return client;
  }

  public static void release() throws IOException {
    client.close();
  }

}
